import React, { Component } from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import LoadingPage from 'widget/LoadingPage';
import {
  DashboardRoot,
  HeadColumnRoot,
  BodyColumnRoot,
  MainColumnRoot,
  SideColumnRoot
} from 'style/AdministratorColumnStyled';
import TableFilter from 'component/Administrators/TableFilter';
import TableColumns from 'component/Administrators/TableColumns';
import RestService from 'service/RequestServices/RestService';
import { URL } from 'service/URLService';
import AdministratorEditModal from 'component/Modals/AdministratorModals/AdministratorEditModal';
import AdministratorCreateUserModal from 'component/Modals/AdministratorModals/AdministratorCreateUserModal';
import Link from 'widget/Link';
import Card from 'widget/Card';
import FaButton from 'widget/FaButton';
import { FaUserPlus } from 'react-icons/fa';
import { H4 } from 'widget/PageHead';
import { Blue, White, GrayLight2 } from 'style/Color';

const BlueContainer = styled(Card)`
  background-color: ${Blue};
  padding: 20px 40px;
`;

const H2 = styled.h2`
  color: ${White};
`;

const SideContainer = styled(Card)`
  padding: 20px;
`;

const UL = styled.ul``;

const LI = styled.li`
  margin-bottom: 16px;
  margin-top: 8px;
`;

const UnLink = styled.p`
  color: ${GrayLight2};
  line-height: 20px;
  font-size: 14px;
  margin: 0;
`;

const TableCard = styled(Card)`
  position: relative;
  min-height: 400px;
`;

const Corner = styled(FaButton)`
  position: absolute;
  z-index: 20;
  right: 0;
  top: 0;
`;

const Table = URL.search('table') || 'users';
const Q = URL.search('q') || '';
const P = URL.search('p') || '1';

class Page extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: {
        list: true,
        counts: true
      },
      modal: {
        id: -1,
        edit: false,
        createUser: false
      },
      list: [],
      counts: 0
    };

    this.handleSearch = q => {
      location.href = q.length > 0 ? `?table=${Table}&q=${q}` : `?table=${Table}`;
    };
    this.handlePagination = p => {
      location.href = `?table=${Table}&p=${p}`;
    };
    this.handleSelect = this.handleSelect.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleClickCorner = this.handleClickCorner.bind(this);
  }

  componentDidMount() {
    if (Q.length > 0) {
      this.getRest();
    } else {
      this.getRestList();
    }

    this.getRestCounts();
  }

  getRest() {
    let { list } = this.state;
    const { loading } = this.state;
    RestService.fetchRest(Table, Q).then(data => {
      list = [data];
      loading.list = false;
      this.setState({ list, loading });
    });
  }

  getRestList() {
    let { list } = this.state;
    const { loading } = this.state;
    const limit = 10;
    const offset = limit * (P - 1);
    RestService.fetchRestList(Table, limit, offset).then(data => {
      list = data;
      loading.list = false;
      this.setState({ list, loading });
    });
  }

  getRestCounts() {
    let { counts } = this.state;
    const { loading } = this.state;
    RestService.fetchRestCounts(Table).then(data => {
      counts = data;
      loading.counts = false;
      this.setState({ counts, loading });
    });
  }

  handleSelect(id) {
    const { modal } = this.state;
    modal.edit = true;
    modal.id = id;
    this.setState({ modal });
  }

  handleClose(modalName) {
    const { modal } = this.state;
    modal[modalName] = false;
    modal.id = -1;
    this.setState({ modal });
  }

  handleClickCorner() {
    const { modal } = this.state;
    modal.createUser = true;
    this.setState({ modal });
  }

  render() {
    const { list, counts, loading, modal } = this.state;
    return (
      <DashboardRoot>
        <HeadColumnRoot>
          <BlueContainer>
            <H2>
              <FormattedMessage id="admin.banner" />
            </H2>
          </BlueContainer>
        </HeadColumnRoot>
        <BodyColumnRoot>
          <SideColumnRoot>
            <SideContainer>
              <H4 style={{ marginBottom: 20 }}>
                <FormattedMessage id="admin.table" />
              </H4>
              <UL>
                {Object.keys(RestService.Tables).map(key => (
                  <LI key={key}>
                    {key === Table ? (
                      <UnLink>{`${key}`}</UnLink>
                    ) : (
                      <Link href={`?table=${key}`}>{`${key}`}</Link>
                    )}
                  </LI>
                ))}
              </UL>
            </SideContainer>
          </SideColumnRoot>
          <MainColumnRoot>
            <TableCard>
              {loading.list || loading.counts ? (
                <LoadingPage />
              ) : (
                [
                  <TableFilter
                    key="filter"
                    Q={Q}
                    P={P}
                    counts={counts}
                    onSearch={this.handleSearch}
                    onPagination={this.handlePagination}
                  />,
                  <TableColumns
                    key="columns"
                    name={Table}
                    data={list}
                    onSelect={this.handleSelect}
                  />,
                  Table === 'users' && (
                    <Corner
                      fa={<FaUserPlus />}
                      bold
                      theme="normal"
                      onClick={this.handleClickCorner}
                    >
                      <FormattedMessage id="admin.create.user" />
                    </Corner>
                  )
                ]
              )}
            </TableCard>
          </MainColumnRoot>
        </BodyColumnRoot>
        {modal.edit && (
          <AdministratorEditModal
            table={Table}
            id={modal.id}
            onClose={() => this.handleClose('edit')}
          />
        )}
        {modal.createUser && (
          <AdministratorCreateUserModal onClose={() => this.handleClose('createUser')} />
        )}
      </DashboardRoot>
    );
  }
}

export default Page;
